package controller

import (
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"fmt"
	mssql "github.com/denisenkom/go-mssqldb"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"net/http"
)

func isPasswordEncrypted(password mssql.VarChar) bool {
	// bcrypt hash is 60 characters long
	return len(password) == 60
}

// 用户登录接口
func Login(ctx *gin.Context) {
	email := ctx.PostForm("email")
	password := ctx.PostForm("password")

	var user model.User
	// 构建数据库查询条件
	DB := common.GetDB()
	DB.Where("email = ?", email).First(&user)

	if user.UID == 0 {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "邮箱不存在",
		})
		return
	}
	//校验密码
	dbPassword := user.Password
	if !isPasswordEncrypted(dbPassword) {
		// 数据库中的密码未加密，需要加密
		hashedDBPassword, err := bcrypt.GenerateFromPassword([]byte(dbPassword), bcrypt.DefaultCost)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"code": 500,
				"msg":  "加密数据库密码失败",
			})
			return
		}
		dbPassword = mssql.VarChar(string(hashedDBPassword))
	}

	if err := bcrypt.CompareHashAndPassword([]byte(dbPassword), []byte(password)); err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 400,
			"msg":  "当前密码错误",
		})
		return
	}
	var avatarFile, coverFile model.AllFile
	DB.Table("all_file").Where("id = ?", user.Avatar).First(&avatarFile)
	DB.Table("all_file").Where("id = ?", user.Cover).First(&coverFile)

	// 构造包含 avatar 和 cover 的 user 返回对象
	userResponse := gin.H{
		"UID":      user.UID,
		"Uname":    user.Uname,
		"Password": user.Password,
		"Email":    user.Email,
		"Avatar": gin.H{
			"id":  user.Avatar,
			"url": avatarFile.FileUrl,
		},
		"Cover": gin.H{
			"id":  user.Cover,
			"url": coverFile.FileUrl,
		},
		"Phone":          user.Phone,
		"Gender":         user.Gender,
		"BackupEmail":    user.BackupEmail,
		"Intro":          user.Intro,
		"Campus":         user.Campus,
		"Major":          user.Major,
		"Permission":     user.Permission,
		"Identity":       user.Identity,
		"PoliticsStatus": user.PoliticsStatus,
		"Grade":          user.Grade,
	}
	response.Success(ctx, gin.H{"user": userResponse}, "登录成功")
}

// 用户注册接口
func Register(ctx *gin.Context) {
	DB := common.GetDB()
	var avatar model.AllFile
	//插入一个记录
	avatar.FileUrl = "https://xybt-1326728101.cos.ap-guangzhou.myqcloud.com/888_1720301231017.jpg"
	avatar.Filename = "头像"
	if err := DB.Create(&avatar).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "数据库插入失败",
		})
		return
	}
	AID := avatar.ID
	var cover model.AllFile
	//插入一个记录
	cover.FileUrl = "https://xybt-1326728101.cos.ap-guangzhou.myqcloud.com/888_1720301195804.jpg"
	cover.Filename = "封面"
	if err := DB.Create(&cover).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "数据库插入失败",
		})
		return
	}
	CID := cover.ID
	var user model.User
	if err := ctx.ShouldBind(&user); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "密码加密失败",
		})
		return
	}
	user.Password = mssql.VarChar(string(hashedPassword))
	user.Avatar = AID
	user.Cover = CID
	if err := DB.Create(&user).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "数据库插入失败",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    200,
		"success": true,
		"msg":     "用户注册成功",
	})
}
func UpdatePassword(ctx *gin.Context) {
	uid := ctx.PostForm("uid")
	currentPassword := ctx.PostForm("currentPassword")
	newPassword := ctx.PostForm("newPassword")
	fmt.Println("UID:", uid)
	fmt.Println("Current Password:", currentPassword)
	fmt.Println("New Password:", newPassword)
	var user model.User
	DB := common.GetDB()
	// 获取用户信息
	DB.Where("uid = ?", uid).First(&user)

	if user.UID == 0 {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	fmt.Println("数据库密码:", user.Password)
	// 校验当前密码
	dbPassword := user.Password

	if !isPasswordEncrypted(dbPassword) {
		// 数据库中的密码未加密，需要加密
		hashedDBPassword, err := bcrypt.GenerateFromPassword([]byte(dbPassword), bcrypt.DefaultCost)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"code": 500,
				"msg":  "加密数据库密码失败",
			})
			return
		}
		dbPassword = mssql.VarChar(string(hashedDBPassword))
	}

	if err := bcrypt.CompareHashAndPassword([]byte(dbPassword), []byte(currentPassword)); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 400,
			"msg":  "当前密码错误",
		})
		return
	}
	////校验密码
	//dbPassword := user.Password
	//hashedDBPassword, error := bcrypt.GenerateFromPassword([]byte(dbPassword), bcrypt.DefaultCost)
	//if error != nil {
	//	// 处理哈希错误
	//	response.Response(ctx, http.StatusInternalServerError, 100, nil, "加密错误！")
	//	return
	//}
	//if err := bcrypt.CompareHashAndPassword(hashedDBPassword, []byte(currentPassword)); err != nil {
	//	ctx.JSON(http.StatusInternalServerError, gin.H{
	//		"code": 400,
	//		"msg":  "密码错误",
	//	})
	//	return
	//}

	// 更新密码
	hashedNewPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "密码加密失败",
		})
		return
	}

	// 使用 map 指定更新的字段，避免更新主键
	updates := map[string]interface{}{
		"password": string(hashedNewPassword),
	}

	if err := DB.Table("users").Where("uid = ?", uid).Updates(updates).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "更新密码失败",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "密码更新成功",
	})
}
